//api 接口地址
const baseUrl = 'https://www.coinsaas.com/mallapi/rebate-server/'


//临时变量
var timerFlg = 0,
	loginTokenFlg = true,
	cookieFlg = true,
	loginUrl = '/pages/access/main' //登录页地址

//上传文件
function httpUpLoad(url, fileUrl) {
	let JSESSIONID = uni.getStorageSync('JSESSIONID')
	if (JSESSIONID) {
		let promise = new Promise(function(resolve, reject) {
			uni.uploadFile({
				url: baseUrl + url,
				filePath: fileUrl,
				name: 'photoFile',
				header: {
					'Cookie': JSESSIONID,
					'Content-Type': 'application/x-www-form-urlencoded',
					'Accept': 'application/json'
				},
				success: res => {
					resolve(JSON.parse(res.data))
				},
				fail: reject => {
					//console.log('uploadfail', reject)
				}
			})
		})
		return promise
	} else {
		//console.log('httpUpLoad 未获取到cookie')
		uni.reLaunch({
			url: loginUrl + "?type=1"
		});
		return new Promise(() => {})
	}
}



/* 
 url:请求地址
 param:请求数据
 cookie:是否带Cookie
 */
function httpRequest(url, param, cookie) {
	let promise = Promise.resolve('Promise==null')
	cookieFlg = cookie
	if (cookie) { //请求带cookie
		promise = httpCookieRequest(url, param).then(res => {
			return analyzeResponse(res);
		})
	} else { //请求不带cookie
		promise = httpNoCookieRequest(url, param).then(res => {
			return analyzeResponse(res);
		})
	}
	return promise;
}


//非cookie请求
function httpNoCookieRequest(url, param) {
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: param,
		method: 'POST',
		header: {
			'Content-Type': 'application/json',
			'Accept': 'application/json'
		}
	}
	console.log('非cookie请求', httpDefaultOpts)
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				let tmpres = res[1];
				tmpres.url = url;
				tmpres.param = param;
				tmpres.cookie = false;
				resolve(tmpres)
			}
		).catch(
			(response) => {
				//console.log("httpUpLoad reject(response)", response)
				reject(response)
			}
		)
	})
	return promise
}

//带Cookie请求
function httpCookieRequest(url, param) {
	let JSESSIONID = uni.getStorageSync('JSESSIONID')
	if (JSESSIONID) {
		let httpDefaultOpts = {
			url: baseUrl + url,
			data: param,
			method: 'POST',
			header: {
				'Cookie': JSESSIONID,
				'Content-Type': 'application/json',
				'Accept': 'application/json'
			}
		}
		console.log('带cookie的请求头', httpDefaultOpts)
		let promise = new Promise(function(resolve, reject) {
			uni.request(httpDefaultOpts).then(
				(res) => {
					let tmpres = res[1];
					tmpres.url = url;
					tmpres.param = param;
					tmpres.cookie = true;
					resolve(tmpres)
				}
			).catch(
				(response) => {
					//console.log("httpCookieRequest reject(response)", response)
					reject(response)
				}
			)
		})
		return promise
	} else {
		//console.log('httpCookieRequest 未获取到cookie 返回login', url)
		uni.reLaunch({
			url: loginUrl + "?type=2"
		});
		return new Promise(() => {})
	}
}

//预处理返回的promise
function analyzeResponse(res) {
	let resdata = new Promise(function(resolve, reject) {
		//console.log('所有数据', res);
		let error = {
			_exceptionLocalizedMessage: "系统异常",
			_tranStatus: false,
			__exceptionMessage:'000000'
		}
		if (res) {
			if (res.statusCode == 200) {
				const res_data = res.data
				if (res_data._tranStatus) {
					resolve(res_data)
				} else {
					//用户未登录处理 或 用户登录失效
					if (res_data._exceptionMessage == '001004' || res_data._exceptionMessage == '001000') {
							resolve(httpTokenRequest(res.url, res.param));
					} else {
						error._exceptionMessage=res_data._exceptionMessage;
						error._exceptionLocalizedMessage = res_data._exceptionLocalizedMessage ? res_data._exceptionLocalizedMessage :
							'调用接口失败'
						//console.log('调用接口失败', res_data._exceptionMessage, error._exceptionLocalizedMessage)
						resolve(error)
					}
				}
			} else {
				error._exceptionLocalizedMessage = res.data
				resolve(error)
			}
		} else {
			//console.log('系统异常res为空')
			error._exceptionLocalizedMessage = '系统异常res为空'
			resolve(error)
		}
	}).catch(function(err) {
		//console.log('catch(error)', err)
	})
	return resdata
}


//用户登录失效，通过token再次登录
const httpTokenRequest = (url, param) => {
	let token = uni.getStorageSync('login_token')
	let error = {
		_exceptionLocalizedMessage: "系统异常",
		_tranStatus: false
	}
	if (token) {
		if (loginTokenFlg) {
			loginTokenFlg = false
			return httpLoginToken(token, url, param);
		} else {
			let promise = new Promise(function(resolve, reject) {
				var timerFlg = setInterval(function() {
					if (loginTokenFlg) {
						clearInterval(timerFlg)
						if (cookieFlg) {
							resolve(httpCookieRequest(url, param).then(rescookie => {
								let flg = rescookie && rescookie.statusCode == 200;
								loginTokenFlg = true;
								return flg ? rescookie.data : error;
							}))
						} else {
							resolve(httpNoCookieRequest(url, param).then(rescookie => {
								let flg = rescookie && rescookie.statusCode == 200;
								loginTokenFlg = true;
								return flg ? rescookie.data : error;
							}))
						}
					}
				}, 1000);
			})
			return promise;
		}
	} else {
		//console.log('用户未登录或用户登录失效，通过token再次登录 未获取到login_token 返回login')
		uni.reLaunch({
			url: loginUrl + "?type=3"
		});
		return new Promise(() => {})
	}
}

function httpLoginToken(ltoken, url, param) {
	const loginparam = {
		loginToken: ltoken
	}
	let promise = new Promise(function(resolve, reject) {
		httpNoCookieRequest('user/tokenLogin', loginparam).then(
			res => {
				if (res) {
					if (res.statusCode == 200) {
						const tmpres = res.data;
						loginTokenFlg = true
						if (tmpres._tranStatus) {
							let cookies = res.header['Set-Cookie'];
							uni.setStorageSync('JSESSIONID', cookies.split(';')[0]);
							uni.setStorageSync('login_token', tmpres._data.loginToken);
							uni.setStorageSync('login_user', JSON.stringify(tmpres._data));
							if (cookieFlg) {
								resolve(httpCookieRequest(url, param).then(rescookie => {
									let flg = rescookie && rescookie.statusCode == 200;
									loginTokenFlg = true;
									return flg ? rescookie.data : error;
								}))
							} else {
								resolve(httpNoCookieRequest(url, param).then(rescookie => {
									let flg = rescookie && rescookie.statusCode == 200;
									loginTokenFlg = true;
									return flg ? rescookie.data : error;
								}))
							}
						} else {
							let tmperror = tmpres._tranStatus ? '' : tmpres._exceptionLocalizedMessage ? tmpres._exceptionLocalizedMessage :
								'httpTokenRequest 调用接口失败';
							//console.log(tmperror + '用户登录失效，通过token再次登录 失败 返回login' + token)
							error._exceptionLocalizedMessage = tmperror;
							resolve(error)
							uni.reLaunch({
								url: loginUrl + "?type=4"
							});
						}
					} else {
						error._exceptionLocalizedMessage = '用户未登录或用户登录失效，通过token再次登录 系统异常 返回login';
						resolve(error)
						uni.reLaunch({
							url: loginUrl + "?type=5"
						});
					}
				} else {
					error._exceptionLocalizedMessage = '用户未登录或用户登录失效，通过token再次登录 系统异常res为空 返回login';
					resolve(error)
					uni.reLaunch({
						url: loginUrl + "?type=6"
					});
				}
			}).catch(function(err) {
			uni.reLaunch({
				url: loginUrl + "?type=7" + JSON.stringify(err)
			});
		})
	});
	return promise
}





//用户登录失效，通过token再次登录
function httpTokenRequest111111(url, param) {
	let token = uni.getStorageSync('login_token')
	if (token) {
		let error = {
			_exceptionLocalizedMessage: "系统异常",
			_tranStatus: false
		}
		const loginparam = {
			loginToken: token
		}
		let promise = new Promise(function(resolve, reject) {
			httpNoCookieRequest('user/tokenLogin', loginparam).then(
				res => {
					if (res) {
						if (res.statusCode == 200) {
							const tmpres = res.data;
							if (tmpres._tranStatus) {
								loginTokenFlg = true
								let cookies = res.header['Set-Cookie'];
								uni.setStorageSync('JSESSIONID', cookies.split(';')[0]);
								uni.setStorageSync('login_token', tmpres._data.loginToken);
								uni.setStorageSync('login_user', JSON.stringify(tmpres._data));
								resolve(httpCookieRequest(url, param).then(rescookie => {
									let flg = rescookie && rescookie.statusCode == 200;
									return flg ? rescookie.data : error;
								}))
							} else {
								let tmperror = tmpres._tranStatus ? '' : tmpres._exceptionLocalizedMessage ? tmpres._exceptionLocalizedMessage :
									'httpTokenRequest 调用接口失败';
								//console.log(tmperror + '用户登录失效，通过token再次登录 失败 返回login' + token)
								error._exceptionLocalizedMessage = tmperror;
								resolve(error)
								uni.reLaunch({
									url: loginUrl + "?type=4"
								});
							}
						} else {
							error._exceptionLocalizedMessage = '用户未登录或用户登录失效，通过token再次登录 系统异常 返回login';
							resolve(error)
							uni.reLaunch({
								url: loginUrl + "?type=5"
							});
						}
					} else {
						error._exceptionLocalizedMessage = '用户未登录或用户登录失效，通过token再次登录 系统异常res为空 返回login';
						resolve(error)
						uni.reLaunch({
							url: loginUrl + "?type=6"
						});
					}
				}).catch(function(err) {
				uni.reLaunch({
					url: loginUrl + "?type=7" + JSON.stringify(err)
				});
			})
		});
		return promise
	} else {
		//console.log('用户未登录或用户登录失效，通过token再次登录 未获取到login_token 返回login')
		uni.reLaunch({
			url: loginUrl + "?type=3"
		});
		return new Promise(() => {})
	}
}


export default {
	httpRequest,
	httpNoCookieRequest,
	httpUpLoad,
}
